﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DBQLTV;

namespace DAO
{
    public class CTThongKeMuonSachDAO
    {
        public bool InsertThongKeMuonSachCT(THONGKEMUONSACH ThongKe, THELOAISACH theLoai)
        {
            using (DBQUANLYTHUVIENEntities entity = new DBQUANLYTHUVIENEntities())
            {
                THONGKEMUONSACHCT ct = entity.THONGKEMUONSACHCTs.FirstOrDefault(o => o.MaTheLoaiSach == theLoai.MaTheLoaiSach);
                THONGKEMUONSACH tke = entity.THONGKEMUONSACHes.FirstOrDefault(o => o.MaTKMS == ThongKe.MaTKMS);
                tke.TongLuotMuon++;
                if (ct == null)
                {
                    THONGKEMUONSACHCT tkms = new THONGKEMUONSACHCT()
                    {
                        MaTKMS = ThongKe.MaTKMS,
                        MaTheLoaiSach = theLoai.MaTheLoaiSach,
                        LuotMuon = 1,
                        TiLe = (int)((float)1 / tke.TongLuotMuon * 100)
                    };
                    entity.THONGKEMUONSACHCTs.AddObject(tkms);
                }
                else
                {
                    ct.LuotMuon++;
                }
               
                entity.SaveChanges();
                UpdateTiLe(tke);
                return true;
            }
        }
        private bool UpdateTiLe(THONGKEMUONSACH ThongKe)
        {
            using (DBQUANLYTHUVIENEntities entity = new DBQUANLYTHUVIENEntities())
            {
                var list = from temp in entity.THONGKEMUONSACHCTs where temp.MaTKMS == ThongKe.MaTKMS select temp;
                if (list == null) return false;
                foreach (THONGKEMUONSACHCT tk in list)
                {
                    float temp = (float)tk.LuotMuon / ThongKe.TongLuotMuon;
                    tk.TiLe = (int)(temp * 100);
                }
                entity.SaveChanges();
                return true;
            }
        }
        public List<THONGKEMUONSACHCT> GetCTThongKeMuonSach(int MaThongKe)
        {
            using (DBQUANLYTHUVIENEntities entity = new DBQUANLYTHUVIENEntities())
            {
                THONGKEMUONSACH tk = entity.THONGKEMUONSACHes.FirstOrDefault(o => o.MaTKMS == MaThongKe);
                return tk.THONGKEMUONSACHCTs.ToList();
            }
        }
    }
}
